/**
 * 反转从位置m到n的链表
 * 链表的第一位就为1，而不是从0开始
 * examlpe: m=2,n=4,head:1->2->3->4->5->6  
 *       => 1->4->3->2->5->6
 * @param {ListNode} head 
 * @param {number} m 
 * @param {number} n 
 */
var reverseBetween = function (head, m, n) {
    // 初始化三个指针
    let prev = null
    let curr = head
    let next = head
    for (let i = 1; i < m; i++) {
        prev = curr
        curr = curr.next
    }

    // 保存反转所需的头尾两个点
    let prev2 = prev
    let curr2 = curr

    for (let i = m; i <= n; i++) {
        // 内部反转
        next = curr.next
        curr.next = prev
        prev = curr
        curr = next
    }

    // 链接头尾
    if (prev2 !== null) {
        prev2.next = prev
    } else {
        // 如果prev2指向空节点，说明反转是从头部开始的，此时需要改变head
        head = prev
    }

    curr2.next = curr
    
    return head
}